package com.colorful.insuranceproject.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.NetWorkImageHolderView;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.adapter.GridImgsAdapter;
import com.colorful.insuranceproject.adapter.HomeHealthInfoAdapter;
import com.colorful.insuranceproject.base.PLEFragment;
import com.colorful.insuranceproject.bean.HealthInfoBean;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.consts.URLConst;
import com.colorful.insuranceproject.home.ConsultDetailsActivity;
import com.colorful.insuranceproject.home.MessageActivity;
import com.colorful.insuranceproject.request.HomeRequest;
import com.lovely3x.common.activities.refresh.CanLoadMore;
import com.lovely3x.common.activities.refresh.CanRefresh;
import com.lovely3x.common.utils.Response;
import com.lovely3x.common.utils.ViewUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/8/18.
 * <p>
 * 资讯板块
 */
public class ConsultFragment extends PLEFragment implements AdapterView.OnItemClickListener, OnItemClickListener,
        CanLoadMore, CanRefresh, View.OnClickListener, GridImgsAdapter.ImageClickedListener {

    private static final int GET_CONSULT_LIST_URL = 0X1;

    private static final int GET_CONSULT_BANNER_URL = 0X2;

    HomeRequest homeRequest;

    /**
     * 资讯列表
     */
    HomeHealthInfoAdapter homeHealthInfoAdapter;

    @Bind(R.id.list_consult)
    ListView lvConsult;

    @Bind(R.id.fl_fragment_list_empty_container)
    ViewGroup viewContainner;

    List<String> mBannerUrls;

    private ConvenientBanner banner;

    @Override
    protected int getContentView() {
        return R.layout.fragment_micro_durg;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this, mRootView);
    }

    @Override
    protected void onViewInitialized() {
        mBannerUrls = new ArrayList<>();
        homeRequest = new HomeRequest(getHandler());
        View head = getLayoutInflater().inflate(R.layout.view_consult_add_head, lvConsult, false);
        lvConsult.addHeaderView(head);
        homeHealthInfoAdapter = new HomeHealthInfoAdapter(null, mActivity);
        homeHealthInfoAdapter.setOnImgViewClickedListener(this);

        lvConsult.setAdapter(homeHealthInfoAdapter);
        banner = (ConvenientBanner) lvConsult.findViewById(R.id.cb_banner);
        lvConsult.setOnItemClickListener(this);
        initBanner();

        // load banner
        homeRequest.getConsultBanner(GET_CONSULT_BANNER_URL);

        // load page data
        onContentStatusChanged(LOADING_CONTENT);
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getData();
    }

    private void getData() {
        if (homeRequest != null) {
            homeRequest.getConsultPageData(currentIndex, GET_CONSULT_LIST_URL);
        }
    }

    @Override
    public void onBeginRefresh() {
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getData();
    }

    @Override
    public void onBeginLoadMore() {
        currentIndex++;
        getData();
    }

    @Override
    protected ViewGroup getEmptyContainerView() {
        return viewContainner;
    }

    private void initBanner() {
        // 设置记录的小标点
        banner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        banner.setPageIndicator(new int[]{R.drawable.banner_page_indicator_ponit_uncheck, R.drawable.banner_page_indicator_point_checked});
        banner.setOnItemClickListener(this);
        banner.startTurning(5000);//5秒一翻页
        ViewGroup.LayoutParams params = banner.getLayoutParams();
        params.width = ViewUtils.getWidth();
        params.height = (int) (params.width * (2 * 1.0f / 5));
        banner.setLayoutParams(params);
        banner.setCanLoop(true);//无限循环
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            // 加载列表
            case GET_CONSULT_LIST_URL:
                handleRefreshState(response, homeHealthInfoAdapter);
                if (response.isSuccessful) {
                    onContentStatusChanged(LOADING_SUCCESSFUL);
                    if (currentIndex == 0 && ((List<HealthInfoBean>) response.obj).size() == 0) {
                        onContentStatusChanged(LOADING_FAILURE, getString(R.string.not_find_data), this);
                    } else {
                        setPageData((List<HealthInfoBean>) response.obj, response.addtional);
                    }
                } else {
                    if (response.addtional == DEFAULT_POST_FIRST_PAGE) {
                        onContentStatusChanged(LOADING_FAILURE, CodeTable.getInstance().getCodeDescription(response), this);
                    }
                }
                break;
            //  加载banner
            case GET_CONSULT_BANNER_URL:
                if (response.isSuccessful) {
                    mBannerUrls = (List<String>) response.obj;
                    if (mBannerUrls.size() <= 1) {
                        banner.setCanLoop(false);//无限循环
                        banner.setPointViewVisible(false);
                    }
                    banner.setPages(new CBViewHolderCreator<Holder<String>>() {
                        @Override
                        public Holder<String> createHolder() {
                            return new NetWorkImageHolderView();
                        }
                    }, mBannerUrls);
                } else {
                    mActivity.showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;
        }
    }

    private void setPageData(List<HealthInfoBean> obj, int index) {
        switch (index) {
            case DEFAULT_POST_FIRST_PAGE:
                homeHealthInfoAdapter.setData(obj);
                break;
            default:
                homeHealthInfoAdapter.addDataToLast(obj);
                break;
        }
    }

    @Override
    protected void restoreInstanceOnCreateBefore(Bundle savedInstanceState) {

    }

    @Override
    protected void restoreInstanceOnCreateAfter(Bundle savedInstanceState) {

    }

    @Override
    public void onItemClick(int position) {
        mActivity.showHTTPURLImgOnNewActivity(mBannerUrls, position);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HealthInfoBean healthInfoBean = (HealthInfoBean) parent.getAdapter().getItem(position);
        mActivity.launchActivity(ConsultDetailsActivity.class, ConsultDetailsActivity.EXTRA_DETAILS, healthInfoBean);
    }

    @Override
    public void onClick(View v) {
        onContentStatusChanged(LOADING_CONTENT);
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getData();
    }

    @Override
    public void onImageClicked(int parentPosition, int position, View view) {
        HealthInfoBean healthInfoBean = homeHealthInfoAdapter.getItem(parentPosition);
        mActivity.launchActivity(ConsultDetailsActivity.class, ConsultDetailsActivity.EXTRA_DETAILS, healthInfoBean);
    }

    @OnClick({R.id.img_guest_service, R.id.img_message})
    void OnClicked(View view) {
        switch (view.getId()) {
            // 客服
            case R.id.img_guest_service:
                final String number = URLConst.CUSTOMER_SERVICE_TELEPHONE_NUMBERS;
                mActivity.showConfirmDialog(getString(R.string.contact_customer_service), number, null, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + getString(R.string.call_constomer_server)));
                        startActivity(intent);
                    }
                }).show();
                break;
            // 消息
            case R.id.img_message:
                mActivity.launchActivity(MessageActivity.class);
                break;

        }
    }

}
